package top.ranzhang.interceptor;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.Size;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.ranzhang.common.context.BaseContext;
import top.ranzhang.common.properties.JwtProperties;
import top.ranzhang.constant.JwtClaimsConstant;
import top.ranzhang.exception.BaseException;
import top.ranzhang.utils.JwtUtil;

@Slf4j
@Component
@RequiredArgsConstructor
public class JwtTokenOtherInterceptor implements HandlerInterceptor {

    private final RedisTemplate redisTemplate;
    private final JwtProperties jwtProperties;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入Other拦截器");
        String token = request.getHeader(jwtProperties.getOtherTokenName());
        if(token == null){
            response.setStatus(401);
            return false;
        }
        String id;
        Claims claims;
        try {
            claims = JwtUtil.parseJWT(jwtProperties.getOtherSecretKey(), token);
            id = claims.get(JwtClaimsConstant.OTHER_ID).toString();
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
        if(redisTemplate.opsForValue().get("token:" + claims.get(JwtClaimsConstant.User_Name)) == null){
            response.setStatus(401);
            throw new BaseException("登录超时");
        }
        BaseContext.setCurrentId(Long.valueOf(id));
        log.info("当前员工id为:{}",id);
        return true;
    }
}
